// packageF/course/chapterList/chapterList.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeNames:[''],
    id:'',
    chapterId:'', //章节ID
    sectionId:'', //小节id
    courseId:'', //课程ID
    goodsId:'', //商品ID
    optionId:'', //规格ID
    videoUrl:'', //视频链接
    deadline:'', 
    chapterData: [], //目录
    chapterInfo:{}, //章节详情
    chapterCount:0,
    sectionCount:0,
    subchapterIndex:0,
    chapterIndex:0,
    page:1,
    videoSecond:0, //视频时间
    videoShow:false,
    isLoadMore: true,
    total_page: 0,
    total:1,
    courseStatus:'', //购买状态
    iPnoneBottomBol:false, //是否是苹果手机
    timer:0,
    canTry:0 //是能否试看 0 否 1是
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.chapterid) {
      this.setData({
        id: options.chapterid,
        chapterId:options.videoid,
        courseId:options.courseid,
        sectionId:options.sectionid
      })
    }
    this.courseInfo();
    this.getiPnoneBottom();
    this.chapterList();
  },
  backClick() {
    wx.navigateBack({ 
      delta: 1, 
    });
  },
  videoPlay() {
      let url = "/packageD/buy/myOrder_v2/myOrder_v2?tag=course";
      let _urlParam = `&goodsId=${this.data.chapterInfo?.goods_id}&optionsId=${this.data.optionId}&total=${this.data.total}`;
      wx.navigateTo({
        url: url + _urlParam
      });
  },
  chapterClose() {
    this.setData({
      videoShow:false
    })
  },
  getiPnoneBottom() {
    let that = this;
    try {
      let value = wx.getStorageSync('iPhoneBottom');
      if (value) {
        that.setData({
          iPnoneBottomBol: true
        });
        // Do something with return value
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  videoTimeData(event) {
    if(!this.data.canTry && this.data.courseStatus == 0) {
      this.setData({
        videoShow: true
      })
      this.videoContext.pause();
      // this.$refs.myVideo.pause();
    }
  },
  timeupdate(event) {
      if( this.data.courseStatus === 0) {
        this.setData({
          videoShow: true
        })
        this.videoContext.pause();
      }
  },
  onChapterChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  sectionOn(event) {
    let {sectionitem,sectionindex,index,itemdata} = {...event.currentTarget.dataset};
    let {section_id,can_try} = {...sectionitem};
    let videoSecond ='';
    // this.canTry = can_try;
    if(this.data.courseStatus === 0) {
      videoSecond = sectionitem.try_time;
    } else {
      videoSecond = sectionitem.video_second;
    }
    this.setData({
      videoSecond:videoSecond,
      canTry:can_try
    })
    if((sectionitem.can_try && this.data.courseStatus === 0) || this.data.courseStatus === 1) {
      this.setData({
        chapterId:itemdata.chapter_id,
        sectionId: section_id,
        subchapterIndex: sectionindex,
        chapterIndex: index
      })
      this.videoUrlData();
    } else {
      this.setData({
        videoShow: true
      })
    }                                                            
  },
  chapterList() {
    let params = {id : this.data.id,page:this.data.page};
    let urlStr = app.getNetAddresss("plugin.course-supply.api.course.chapter-list");
    app._postNetWork({
      url: urlStr,
      data: params,
      success: (resdata) => {
        let res = resdata.data;
        wx.hideLoading();
        wx.hideNavigationBarLoading();//隐藏导航条加载动画
        //停止下拉刷新
        wx.stopPullDownRefresh();
        if (res.result == 1) {
          this.data.isLoadMore = true;
          this.data.totalPage = res.data.last_page;
          if (!this.data.totalPage) {
            this.data.totalPage = 0;
          }
          let videoSecond = '';
          let chapterData =  res.data.data;
          if(res.data?.course_status === 0) {
            videoSecond = Number(chapterData[0]?.section[0]?.try_time);
          } else {
            videoSecond = Number(chapterData[0]?.section[0]?.video_second);
          }
          if(!this.data.courseId) {
            this.data.courseId = this.chapterData[0]?.course_id;
          }
          if(!this.data.chapterId) {
            this.data.chapterId = this.chapterData[0]?.chapter_id;
          }
          if(!this.data.sectionId) {
            this.data.sectionId = this.chapterData[0]?.section[0]?.section_id;
          }
          this.setData({
            sectionCount:res.data?.section_count,
            chapterCount:res.data?.chapter_count,
            chapterData: res.data.data,
            ['activeNames[0]']:chapterData[0]?.id,
            canTry: chapterData[0]?.section[0]?.can_try,
            courseStatus: res.data?.course_status,
            deadline: this.timestampToTime(res.data?.deadline),
            videoSecond:videoSecond
          });
          this.videoUrlData();
        } else {
          this.data.page = this.data.page - 1;
          this.isLoadMore = false;
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); // 时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = this.change(date.getDate()) + ' ';
    let h = this.change(date.getHours()) + ':';
    let m = this.change(date.getMinutes());
    return Y + M + D + h + m;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.totalPage) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let params = {id : this.data.id,page:this.data.page};
      let urlStr = app.getNetAddresss("plugin.course-supply.api.course.chapter-list");
      app._getNetWork({
        url: urlStr,
        data: params,
        success: (resdata) => {
          let res = resdata.data;
          let list = res.data.data;
          if (res.result == 1) {
            this.data.isLoadMore = true;
            this.setData({
              chapterData : this.data.chapterData.concat(list),
            });
          } else {
            this.data.page = this.data.page - 1;
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1500
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  courseInfo() {
    let params = {id : this.data.id,basic_info:1};
    let urlStr = app.getNetAddresss("plugin.course-supply.api.course.info");
    app._postNetWork({
      url: urlStr,
      data: params,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.setData({
            chapterInfo: res.data,
            pluginSetting: res.basic_info?.plugin_setting
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  videoUrlData() {
    let params = {
      course_id: this.data.courseId,
      chapter_id: this.data.chapterId,
      section_id: this.data.sectionId
    };
    let urlStr = app.getNetAddresss("plugin.course-supply.api.course.get-video-url");
    app._postNetWork({
      url: urlStr,
      data: params,
      success: (resdata) => {
        let res = resdata?.data;
        let data = res?.data;
        if (res.result == 1) {
          this.setData({
            videoUrl: data?.data?.url || "",
            optionId: data?.option_id
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.videoContext = wx.createVideoContext('myVideo');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading();
     //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
     wx.showLoading({
      title: '刷新中...',
    })
    this.setData({
      page:1
    })
    this.getCourseList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log('没有更多了');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.chapterInfo?.name,
      imageUrl:this.data.chapterInfo?.cover,
      path: `/packageF/course/chapterList/chapterList?chapterid=${this.data.id}&courseid=${this.data.courseId}&sectionid=${this.data.sectionId}&videoid=${this.data.chapterId}`
    };
  },
  onShareTimeline() {
    return {
      title: this.data.chapterInfo?.name,
      imageUrl:this.data.chapterInfo?.cover,
      path: `/packageF/course/chapterList/chapterList?chapterid=${this.data.id}&courseid=${this.data.courseId}&sectionid=${this.data.sectionId}&videoid=${this.data.chapterId}`
    };
  }
})